import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:openvalley_smart_agriculture/constants/api_config.dart';
import 'package:openvalley_smart_agriculture/utils/JsonUtil.dart';

import '../models/json/base_api.dart';

Map<String, BaseApi> cache = {};

Future<T?> apiGetModel<T extends BaseApi>(
    {Map<String, dynamic>? addParams}) async {
  var configData = getConfigData<T>();
  if (cache[configData.apiName] != null) {
    log("使用了${configData.apiName}的缓存。");
    return cache[configData.apiName] as T;
  }
  log("${configData.apiName}暂无请求，开始请求。");
  Map<String, dynamic> params = configData.defaultParams;
  if (addParams != null && addParams.isNotEmpty) {
    params.addAll(addParams);
  }
  Uri uri;
  if (configData.isHttps) {
    uri = Uri.https(configData.host, configData.path, params);
  } else {
    uri = Uri.http(configData.host, configData.path, params);
  }

  var httpClient = HttpClient();
  // 忽略 SSL 验证
  httpClient.badCertificateCallback = (X509Certificate cert, String host, int port) => true;
  // 发起 GET 请求
  var request = await httpClient.getUrl(uri);
  // 发送请求并获取响应
  var response = await request.close();
  var responseBody = await response.transform(utf8.decoder).join();
  if (response.statusCode == 200) {
    var t = fromJson<T>(responseBody);
    cache[configData.apiName] = t as BaseApi;
    print("请求成功，请求结果：$responseBody");
    log("请求成功，请求结果：$responseBody");
    return t;
  } else {
    log("请求异常:errorCode=${response.statusCode},msg=$responseBody");
    print("请求异常:errorCode=${response.statusCode},msg=$responseBody");
    return null;
  }
}
